# -*- coding: UTF-8 -*-
import direct.directbase.DirectStart
import panda3d.core as CORE
import sys
class Mouse:
    def __init__(self,game_obj,player): 
        self.game_obj = game_obj
        self.player = player
        pass
    
    def initMouse(self):
        
        self.pickerNode=CORE.CollisionNode('mouseRay') 
        self.pickerNP=camera.attachNewNode(self.pickerNode) 
        self.queue=CORE.CollisionHandlerQueue()
        #对可见几何体的碰撞检测
        self.pickerNode.setFromCollideMask(CORE.GeomNode.getDefaultCollideMask()) 
        self.pickerRay=CORE.CollisionRay() 
        self.pickerNode.addSolid(self.pickerRay) 
        self.game_obj.CTrav.addCollider(self.pickerNP, self.queue) 
        
        self.game_obj.accept("mouse1", self.selectObj)
        self.game_obj.accept("mouse3", self.gotoPos)
        self.game_obj.accept("wheel_up",self.viewAdjustUp)
        self.game_obj.accept("wheel_down",self.viewAdjustDown)
    VIEW_IVAL = 0.4    
    def viewAdjustUp(self):
        base.camera.setZ(base.camera.getZ()+Mouse.VIEW_IVAL)
        pass
    def viewAdjustDown(self):
        base.camera.setZ(base.camera.getZ()-Mouse.VIEW_IVAL)
        pass
    
    #该函数为物体设置一个标志，让它可以拾取
    def makePickable(self,newObj): 
        newObj.setTag('pickable','true')
    
    #获取地面与鼠标的交点
    def gotoPos(self):
            
        mpos = base.mouseWatcherNode.getMouse()
        self.pickerRay.setFromLens(base.camNode, mpos.getX(),mpos.getY())
        self.game_obj.CTrav.traverse(render) 
        if self.queue.getNumEntries() > 0:
            obj_pos = self.queue.getEntry(0).getSurfacePoint(render)
            start_pos = self.player.ralph.getPos()
            self.player.ralph.setPos(obj_pos)
            #self.player.move(obj_pos,start_pos)
        
    def selectObj(self):
        mpos = base.mouseWatcherNode.getMouse()
        self.pickedObj=None #记得先清零
        #自动根据二维坐标建立射线  使射线从摄影机发出，指向鼠标的屏幕坐标
        self.pickerRay.setFromLens(base.camNode, mpos.getX(),mpos.getY()) 
        self.game_obj.CTrav.traverse(render) 
        if self.queue.getNumEntries() > 0: 
            self.queue.sortEntries() 
            self.pickedObj=self.queue.getEntry(0).getIntoNodePath() 
            parent=self.pickedObj.getParent() 
            self.pickedObj=None 
        
        while parent != render: 
            if parent.getTag('pickable')=='true': 
                self.pickedObj=parent
                print parent
                return parent 
            else: 
                parent=parent.getParent() 
        return None 
        pass